"""
自定义样式的输入框组件
"""
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

from app.ui.theme import Theme


class StyledLineEdit(QLineEdit):
    """
    自定义样式的输入框组件
    """
    
    # 自定义信号
    textChangedDebounced = pyqtSignal(str)
    
    def __init__(self, placeholder="", parent=None):
        """
        初始化输入框
        
        @param placeholder: 占位文本
        @param parent: 父组件
        """
        super().__init__(parent)
        
        # 设置占位文本
        self.setPlaceholderText(placeholder)
        
        # 设置字体
        self.setFont(Theme.get_font())
        
        # 应用样式
        self.update_style()
        
        # 防抖计时器
        self._debounce_timer = None
        self.textChanged.connect(self._on_text_changed)
    
    def update_style(self):
        """
        更新输入框样式
        """
        # 获取主题颜色
        bg_color = Theme.get_color("card_background")
        text_color = Theme.get_color("text_primary")
        border_color = Theme.get_color("border")
        focus_color = Theme.get_color("primary")
        placeholder_color = Theme.get_color("text_secondary")
        
        # 设置样式表
        self.setStyleSheet(f"""
            QLineEdit {{
                background-color: {bg_color};
                color: {text_color};
                border: 1px solid {border_color};
                border-radius: 4px;
                padding: 8px;
            }}
            
            QLineEdit:focus {{
                border: 1px solid {focus_color};
            }}
            
            QLineEdit::placeholder {{
                color: {placeholder_color};
            }}
            
            QLineEdit:disabled {{
                background-color: {Theme.get_color("disabled")};
                color: {Theme.get_color("text_disabled")};
            }}
        """)
    
    def _on_text_changed(self, text):
        """
        文本变化处理函数
        
        @param text: 当前文本
        """
        # 取消之前的计时器
        if self._debounce_timer:
            self.killTimer(self._debounce_timer)
        
        # 设置新的计时器，300ms 后触发防抖信号
        self._debounce_timer = self.startTimer(300)
    
    def timerEvent(self, event):
        """
        计时器事件处理函数
        
        @param event: 计时器事件
        """
        # 触发防抖信号
        self.textChangedDebounced.emit(self.text())
        
        # 取消计时器
        self.killTimer(event.timerId())
        self._debounce_timer = None 